package com.kaba.gzlcmxgl.controller;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.kaba.bean.Activiti_lssq;
import com.kaba.bean.Activiti_wddb;
import com.kaba.bean.ResponseResult;
import com.kaba.bean.mongodb.ZuoPin;
import com.kaba.zplb.service.WorksService;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricActivityInstanceQuery;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@RestController
@RequestMapping("activiti")
@CrossOrigin
public class ActivitiController {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private WorksService worksService1;

    @GetMapping(value = "/startProcess")
    @ResponseBody
    public void startProcess() {
        //先进行判断数据库此流程是否被部署
        //进行部署
        Deployment deployment = repositoryService.createDeployment()
                //添加bpmn资源
                .addClasspathResource("processes/processes01.bpmn")
                .addClasspathResource("processes/processes01.png")
                .name("作品流程审批")
                .deploy();
        //输出部署一些信息
        System.out.println("流程部署id:" + deployment.getId());
        System.out.println("流程部署名称:" + deployment.getName());


        //创建流程实例 流程定义的key
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("myProcess1");
        System.out.println("流程部署id:" + processInstance.getDeploymentId());
        System.out.println("流程部署id:" + processInstance.getProcessDefinitionId());
        System.out.println("流程实例id:" + processInstance.getId());
        System.out.println("活动id:" + processInstance.getActivityId());


    }

    /*
     *基本定义流程
     */
    @RequestMapping(value = "/definition")
    public ResponseResult definition(String zuopinid,String username) {
        System.out.println("BusinessKey:"+zuopinid);
        System.out.println("当前负责人:"+username);
        RuntimeService runtimeService = processEngine.getRuntimeService();
        Map<String,Object> map=new HashMap<>();
        map.put("username",username);
        map.put("lisi",username);
        map.put("zhaoliu",username);
        //流程定义完成
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("myProcess1", zuopinid,map);
        //根据businesskey查询当前申请的作品信息，根据作品id 修改作品表的状态为 1
        System.out.println("新定义的流程："+processInstance);
        //1,根据负责人，查询对象task
        List<Task> task = taskService.createTaskQuery().taskAssignee(username).list();
        //2.使用任务ID，获取实例ID
        for (Task task1 : task) {
            //流程实例id
            String processInstanceId = task1.getProcessInstanceId();
            //3.使用流程实例id，查询当前正在执行的任务节点
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            //获取business_key
            String business_key = pi.getBusinessKey();
            System.out.println("business_key主键id："+business_key);
            //根据业务表id查询当前业务信息
            ZuoPin work = worksService1.queryById(business_key);
            System.out.println("当前申请的业务id："+work.getZuopinid());
            System.out.println("当前申请的作品名称："+work.getTitle());
            System.out.println("当前审批状态："+work.getStates());
            System.out.println("流程实例id："+processInstanceId);
            //修改审批状态state
            //修改审批状态state
            UpdateWrapper updateWrapper=new UpdateWrapper();
            updateWrapper.eq("zuopinid",work.getZuopinid());
            updateWrapper.set("states","1");
            worksService1.update(updateWrapper);
            processEngine.getTaskService()//管理员进行名次申请
                    .complete(task1.getId());


        }


        return ResponseResult.success();
    }


    /**
     * 我的待办 TASK表
     *
     * 根据当前人Assigness查询 完成个人任务
     *
     */
   /* @RequestMapping(value = "/taskQuery")
    @ResponseBody
    public ResponseResult taskQuery(String username) {
        //根据流程定义的 key, 负责人 assignee来实现当前用户的任务列表查询
        List<Task> taskList = taskService.createTaskQuery()
                //流程的key
                //.processDefinitionKey("myProcess05")

                //任务负责人
                .taskAssignee(username)
                .list();
        List<Activiti_wddb> wddblist=new ArrayList<>();

        System.out.println("当前人待办任务："+taskList);
        for (Task task : taskList) {
            //流程实例id
            String processInstanceId = task.getProcessInstanceId();
            //3.使用流程实例，查询
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            //获取business_key
            String business_key = pi.getBusinessKey();
            //查询当前申请审批的作品
            ZuoPin work = worksService1.queryById(business_key);
            Activiti_wddb wddb=new Activiti_wddb();
            //编号 实例id
            wddb.setDaibanid(task.getProcessInstanceId());
            //实例id
            //申请人
            wddb.setDbname(task.getAssignee());
            //提交申请时间
            wddb.setCreatetime(task.getCreateTime());
            //当前节点名称
            wddb.setJdname(task.getName());
            //作品描述
            wddb.setReason(work.getExplain());
            //标题
            wddb.setBiaoti(work.getTitle());
            //状态
            wddb.setStates("1");
            System.out.println("流程实例id:" + task.getProcessInstanceId());
            System.out.println("任务负责人:" + task.getAssignee());
            System.out.println("任务id:" + task.getId());
            System.out.println("任务名称:" + task.getName());
            wddblist.add(wddb);
            System.out.println(wddblist);
        }


        return ResponseResult.success(wddblist);

    }*/


    @GetMapping(value = "/createTaskQuery")
    public void createTaskQuery() {
        //根据流程定义的 key, 负责人 assignee来实现当前用户的任务列表查询
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey("myProcess")
                .taskAssignee("李四")

                .list();
        for (Task task : taskList) {
            System.out.println("流程实例id:" + task.getProcessInstanceId());
            System.out.println("任务负责人:" + task.getAssignee());
            System.out.println("任务id:" + task.getId());
            System.out.println("任务名称:" + task.getName());
            taskService.complete(task.getId());
        }


    }
    /**
     * 我的待办 TASK表
     *
     * 根据当前人Assigness查询 完成个人任务
     *
     */
    @GetMapping(value ="/Querytask")
    public ResponseResult Querytask(String username) {
        List<Task> taskList  = taskService.createTaskQuery()
                .taskAssignee(username)
                .list();

        List<Activiti_wddb> activitiWddbs= new ArrayList<>();
        for (Task task : taskList) {
            //流程实例id
            String processInstanceId = task.getProcessInstanceId();
            //3.使用流程实例，查询
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            //获取business_key
            String business_key = pi.getBusinessKey();
            //查询当前申请审批的作品
            ZuoPin work = worksService1.queryById(business_key);
            Activiti_wddb wddb=new Activiti_wddb();
            //编号 实例id
            wddb.setDaibanid(task.getProcessInstanceId());
            //申请人
            wddb.setDbname(task.getAssignee());
            //提交申请时间
            wddb.setCreatetime(task.getCreateTime());
            //当前节点名称
            wddb.setJdname(task.getName());
            //作品描述
            wddb.setReason(work.getExplain());
            //标题
            wddb.setBiaoti(work.getTitle());
            //状态
            wddb.setStates(work.getStates());
            //作品名次
            wddb.setZuopinmingci(work.getRanking());
            //作品奖金
            wddb.setZuopinjiangjin(work.getBonus());
            System.out.println("流程实例id:" + task.getProcessInstanceId());
            System.out.println("任务负责人:" + task.getAssignee());
            System.out.println("任务id:" + task.getId());
            System.out.println("任务名称:" + task.getName());
            activitiWddbs.add(wddb);
            System.out.println(activitiWddbs);
        }


        return ResponseResult.success(activitiWddbs);

    }

    /**
     * 我的已办 TASKINST表
     */
   /* @GetMapping(value ="/Queryactinst")
    public ResponseResult Queryactinst(String username) {
//得到processEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //historyService
        HistoryService historyService = processEngine.getHistoryService();
        //得到 historicActivityInstanceQuery
        HistoricActivityInstanceQuery historicActivityInstanceQuery = historyService.createHistoricActivityInstanceQuery();
        historicActivityInstanceQuery.taskAssignee(username);
        List<HistoricActivityInstance> list = historicActivityInstanceQuery.list();

        List<Activiti_wdyb> actwdyb = new ArrayList<>();
        for (HistoricActivityInstance ai : list) {
            Activiti_wdyb activitiWdyb = new Activiti_wdyb();
            //activitiId
            System.out.println(ai.getActivityId());
            //id
            activitiWdyb.setYbid(ai.getId());
            //所属节点
            activitiWdyb.setSsjd(ai.getActivityName());
            //开始时间
            activitiWdyb.setCreatetime(ai.getStartTime());
            //状态
            activitiWdyb.setStates("2");
            //发起人
            activitiWdyb.setFaqiname("张三");
            //办理人
            activitiWdyb.setYbname(ai.getAssignee());
            actwdyb.add(activitiWdyb);

            System.out.println(ai.getId());
            //名字
            System.out.println(ai.getActivityName());
            //当前时间
            System.out.println(ai.getStartTime().toString());
            //结束时间
            System.out.println(ai.getEndTime());
            //流程定义id
            System.out.println(ai.getProcessDefinitionId());
            //实例id
            System.out.println(ai.getProcessInstanceId());
        }
        return ResponseResult.success(actwdyb);
    }*/

    /*
     * 我的已办
     * */
    @RequestMapping(value = "/hisQuery")

    @JsonIgnoreProperties(value = {"handler"})
    public ResponseResult hisQuery(String username) {
        System.out.println("当前账号："+username);
        //得到processEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //historyService
        HistoryService historyService = processEngine.getHistoryService();
        HistoricActivityInstanceQuery historicActivityInstanceQuery = historyService.createHistoricActivityInstanceQuery();
        //根据负责人Assignee查询
        historicActivityInstanceQuery.taskAssignee(username);
        List<HistoricActivityInstance> list = historicActivityInstanceQuery.list();
        System.out.println("已办业务："+list);
        //历史申请
        List<Activiti_lssq> lssqlist=new ArrayList<>();

        for (HistoricActivityInstance ai : list) {

            String processInstanceId = ai.getProcessInstanceId();
            //3.使用流程实例id，查询任务节点
            HistoricProcessInstance pi = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            //获取business_key
            String business_key = pi.getBusinessKey();
            //根据businesskey（业务表与Activiti关联的外键）查询当前业务信息
            ZuoPin work = worksService1.queryById(business_key);
            System.out.println("申请的作品名称："+work.getTitle());

            //历史申请对象
            Activiti_lssq lssq=new Activiti_lssq();
            //activitiId //申请id
            lssq.setShenqingid(ai.getProcessInstanceId());
            //标题
            lssq.setMyname(ai.getActivityName());
            //开始时间
            lssq.setStarttime(ai.getStartTime());
            //结束时间
            lssq.setEndtime(ai.getEndTime());
            //作品名称
            lssq.setZhuoping(work.getTitle());
            System.out.println(ai.getActivityId());
            System.out.println("Assigness:"+ai.getAssignee());
            System.out.println("TaskId:"+ai.getTaskId());
            //名字
            System.out.println(ai.getActivityName());
            //当前时间
            System.out.println(ai.getStartTime().toString());
            //结束时间
            System.out.println(ai.getEndTime().toString());
            //流程定义id
            System.out.println(ai.getProcessDefinitionId());
            //实例id
            System.out.println(ai.getProcessInstanceId());
            lssqlist.add(lssq);
        }

        System.out.println("历史申请："+lssqlist);
        return  ResponseResult.success(lssqlist);
    }
    /**完成我的任务*/
    @GetMapping(value = "/mycomplete")
    @CrossOrigin
    @ResponseBody
    public ResponseResult mycomplete(String daibanid){
        System.out.println("实例id："+daibanid);
        //1.传入实例id查询出当前task对象
        List<Task> taskList=taskService.createTaskQuery().processInstanceId(daibanid).list();
        //2.使用流程实例，查询
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(daibanid).singleResult();
        //3.获取business_key
        String business_key = pi.getBusinessKey();
        System.out.println("业务主键id:"+business_key);
        System.out.println("完成前："+taskList);
        for (Task task : taskList) {
            processEngine.getTaskService()//与正在执行的任务管理相关的Service
                    .complete(task.getId());
        }
        //完成任务之后再次查询
        List<Task> taskList1=taskService.createTaskQuery().processInstanceId(daibanid).list();
        System.out.println("完成后："+taskList1);
        if (taskList1.size()==0){
            //根据业务表id查询当前业务信息
            ZuoPin work = worksService1.queryById(business_key);
            System.out.println("当前申请的业务id："+work.getZuopinid());
            System.out.println("当前申请的作品名称："+work.getTitle());
            System.out.println("当前审批状态："+work.getStates());
            //修改审批状态state
            UpdateWrapper updateWrapper=new UpdateWrapper();
            updateWrapper.eq("zuopinid",work.getZuopinid());
            updateWrapper.set("states","2");
            worksService1.update(updateWrapper);

        }


        return ResponseResult.success(daibanid);
    }

    /*
     * 驳回
     * */
    @RequestMapping("/deleteComplete")
    public ResponseResult deleteComplete(String daibanid,String Suggestions){
        Suggestions="不通过";
        //1.传入实例id查询出当前task对象
        List<Task> taskList=taskService.createTaskQuery().processInstanceId(daibanid).list();
        //2.使用流程实例，查询
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(daibanid).singleResult();
        //3.获取business_key
        String business_key = pi.getBusinessKey();
        System.out.println("业务主键id:"+business_key);
        System.out.println("流程实例id:"+daibanid);
        System.out.println("流程实例id:"+daibanid);
        //根据流程实例id删除当前流程
        runtimeService.deleteProcessInstance(daibanid,Suggestions);
        //修改状态
        ZuoPin work = worksService1.queryById(business_key);
        //修改审批状态state
        UpdateWrapper updateWrapper=new UpdateWrapper();
        updateWrapper.eq("zuopinid",work.getZuopinid());
        updateWrapper.set("states","3");
        worksService1.update(updateWrapper);
        return ResponseResult.success();
    }

   /* @RequestMapping(value = "/mycomplete")
    public  ResponseResult mycomplete( String daibanid){
        System.out.println("任务id："+daibanid);
        processEngine.getTaskService()
                .complete(daibanid);
        return  ResponseResult.success(daibanid);
    }*/
   /*
    * 挂起流程和激活（全部流程）
    * */
   @RequestMapping(value = "/Process")
   @ResponseBody
   public ResponseResult Process (){
       //查询流程定义 获取流程定义的查询对象
       ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery()
               .processDefinitionKey("myProcess")
               .singleResult();
       //获取当前流程定义是否都为挂起状态
       boolean suspended = processDefinition.isSuspended();
       //获取流程定义id
       String definitionId = processDefinition.getId();
       //如果挂起 改为激活
       if (suspended){

           repositoryService.activateProcessDefinitionById(definitionId,true,null);

       }else{
           //如果激活  改为挂起
           repositoryService.suspendProcessDefinitionById(definitionId,true,null);
       }
       return ResponseResult.success();
   }

    /*
     * 挂起流程和激活（单个流程）
     * */
    @RequestMapping(value = "/suspendsingle")
    @ResponseBody
    public ResponseResult suspendsingle (){
        //查询流程定义 获取流程定义的查询对象
        ProcessInstance processInstance=runtimeService.createProcessInstanceQuery()
                .processInstanceId(""/*流程实例id Taks表中的procinstid*/)
                .singleResult();
        //获取当前流程定义是否都为挂起状态
        boolean suspended = processInstance.isSuspended();
        //获取流程定义id
        String definitionId = processInstance.getId();
        //如果暂停 改为激活
        if (suspended){

            runtimeService.activateProcessInstanceById(definitionId);

        }else{
            //如果激活  改为暂停
            runtimeService.suspendProcessInstanceById(definitionId);
        }
        return ResponseResult.success();
    }


}
